﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Web;
using System.Windows.Forms;
using Qiniu.IO.Resumable;
using Qiniu.RPC;
using Qiniu.RS;
using Qiniu.RSF;


namespace SpreadDesigner
{
    /// <summary>
    /// 七牛云存储类库
    /// </summary>
    public class QiniuWrapLib
    {
        #region Single
        private QiniuWrapLib()
        {
            Qiniu.Conf.Config.ACCESS_KEY = "5iujaJ62Q9eQc94uF0sgFzxwVTP-9c_hKq_2jC-j";
            Qiniu.Conf.Config.SECRET_KEY = "RMRV45M6J-GpLvz2pAgndn3i-MmTxnDcJMqwsWKG";
        }
        public static QiniuWrapLib mSingle = new QiniuWrapLib();
        #endregion

        private const string Bucket = "grapecity";
        private const string Domain = Bucket + ".qiniudn.com";

        #region List

        /// <summary>
        /// 获得当前文件列表
        /// </summary>
        /// <param name="bucket"></param>
        public void List(ListView listView1, string bucket = Bucket)
        {
            Qiniu.RSF.RSFClient rsf = new Qiniu.RSF.RSFClient(bucket);
            rsf.Prefix = "";
            rsf.Limit = 100;
            List<DumpItem> items;
            while ((items = rsf.Next()) != null)
            {
                foreach (DumpItem item in items)
                {
                    Stat(listView1, item.Key, bucket);
                }
            }
        }

        public void Stat(ListView listView1, string key, string bucket = Bucket)
        {

            RSClient client = new RSClient();
            Entry entry = client.Stat(new EntryPath(bucket, key));
            if (entry.OK)
            {
                ListViewItem item = new ListViewItem(new string[]{key, entry.MimeType, 
                    DateTime.FromFileTime(entry.PutTime).ToLongDateString(), entry.Fsize.ToString()});
                listView1.Items.Add(item);
            }
            else
            {
                Console.WriteLine("Failed to Stat");
            }
        }
        #endregion

        #region Upload
        public bool Upload(string path)
        {
            bool flag = false;
            Settings putSetting = new Settings();
            ResumablePutExtra extra = new ResumablePutExtra();
            NameValueCollection nc = new NameValueCollection();
            nc.Add("x:username", "qiniu");
            extra.CallbackParams = nc;
            ResumablePut target = new ResumablePut(putSetting, extra);
            string upToken = new PutPolicy(Bucket).Token(new Qiniu.Auth.digest.Mac());
            string key = path.Substring(path.LastIndexOf('\\') + 1, path.Length - path.LastIndexOf('\\') - 1);
            target.PutFinished += new EventHandler<CallRet>((o, e) =>
            {
                if (e.OK)
                {
                    flag = true;
                }
            });

            target.PutFailure += new EventHandler<CallRet>((a, b) =>
            {
                flag = false;
            });

            CallRet ret = target.PutFile(upToken, path, key);
            return flag;
        }
        #endregion

        #region DownLoad
        public string DownLoad(string key1, string domain = Domain)
        {
            string baseUrl = GetPolicy.MakeBaseUrl(domain, key1);
            string private_url = GetPolicy.MakeRequest(baseUrl);
            private_url = HttpUtility.UrlPathEncode(private_url);

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(private_url);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream stream = response.GetResponseStream();
                string newFile = AppDomain.CurrentDomain.BaseDirectory + key1;
                FileStream write = new FileStream(newFile, FileMode.OpenOrCreate);

                stream.CopyTo(write);

                stream.Close();
                write.Close();

                return newFile;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Assert(false, ex.Message);
                return "";
            }
        }

        #endregion

        #region Delete
        /// <summary>
        /// 删除单个文件
        /// </summary>
        /// <param name="bucket">文件所在的空间名</param>
        /// <param name="key">文件key</param>
        public bool Delete(string key, string bucket = Bucket)
        {
            RSClient client = new RSClient();
            CallRet ret = client.Delete(new EntryPath(bucket, key));
            return ret.OK;
        }
        #endregion
    }
}
